<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use App\Model\Users;
use Auth;

class LoginController extends Controller
{
    use AuthenticatesUsers;
    protected $redirectTo = '/Admin/index'; //成功后跳转

    public function __construct()
    {
        $this->middleware('guest')->except('logout');
    }

    public function showLoginForm() //视图
    {
        if(Auth::check()){
            return redirect()->to('/Admin/index');
        }
        return view('admin.login');
    }


    //验证
    protected function validateLogin(Request $request)
    {

    	//验证错误信息
        $errMsg = [
        	$this->username().'.required' => '用户名不能为空！',
        	$this->username().'.string' => '用户名不存在！',
        	'password.required' => '密码不能为空！',
        	'password.string' => '密码错误！',
        	'code.required' => '验证码不能为空！',
        	'code.captcha' => '验证码错误！',
        ];

        $this->validate($request, [
            $this->username() => 'required|string',
            'password' => 'required|string',
            'code' => 'required|captcha',
        ],$errMsg);

    }

    public function username() //将email验证改为username
    {
        return 'username';
    }

    // 登录验证重写
    protected function attemptLogin(Request $request)
    {
        $is_login = $this->guard()->attempt(
            $this->credentials($request), $request->has('remember')
        );

        //  判断是否登录
        if($is_login){
            $users = new Users;
            $login_ip = sprintf("%u", ip2long($request->ip())); //转化ip
            $user_info = Auth::user();
            $data = [
                'login_ip' => $login_ip,
                'login_time' => time(),
                'last_login_time' => $user_info->login_time,
            ];

            $users->where('id',$user_info->id)->update($data);
        }

        return $is_login;
    }

}
